<template>
  <el-drawer
	v-model="dialog.visible"
	:title="dialog.title"
    size="60%"
    destroy-on-close
	@close="closeDialog"
	:close-on-click-modal="false"
  >
    <div class="drawer-content">
		<el-scrollbar >
		<div style="margin-bottom: 18px;">
			<span class="title-form_primary">SQL信息</span>
		</div>	
		
      <div class="sql-info">
        <div class="info-item">
          <span class="label">SQL名称：</span>
          <span>{{ testRow.name }}</span>
        </div>
		
        <div class="info-item">
          <span class="label">SQL标识：</span>
          <span>{{ testRow.identifier }}</span>
        </div>
		
        <div class="info-item">
          <span class="label">SQL执行：</span>
		  <span>
			<DictLabel v-model="testRow.exec" code="sql_execute_type" />
		  </span>
        </div>
      </div>
	  
	  <div style="margin-bottom: 18px;">
	  	<span class="title-form_primary">SQL参数</span>
	  </div>	
	  
	  <!-- SQL参数表单 -->
	  <div class="param-form" v-if="paramField.length > 0">
		<el-form 
		  ref="paramFormRef"
		  :model="paramValues"
		  label-width="120px"
		>
		  <el-form-item 
			v-for="param in paramField" 
			:key="param.identifier"
			:label="param.name"
			:prop="param.identifier"
			:rules="param.required=='1' && param.fieldValueFormSrc=='input'  ? [{ required: true, message: `请输入${param.name}`, trigger: 'blur' }] : []"
		  >
			<!-- 字符串类型 -->
			<el-input 
			  v-if="param.type === 'string'"
			  v-model="paramValues[param.identifier]"
			  :placeholder="`请输入${param.name}`"
			  :readonly="param.fieldValueFormSrc!='input'"
			/>
			
			<!-- 数值类型 -->
			<el-input-number 
			  v-else-if="param.type === 'number'"
			  v-model="paramValues[param.identifier]"
			  :placeholder="`请输入${param.name}`"
			  :readonly="param.fieldValueFormSrc!='input'"
			/>
			
			<!-- 布尔类型 -->
			<el-switch
			  v-else-if="param.type === 'boolean'"
			  v-model="paramValues[param.identifier]"
			  :readonly="param.fieldValueFormSrc!='input'"
			/>
			
			<!-- 日期类型 -->
			<el-date-picker
			  v-else-if="param.type === 'date'"
			  v-model="paramValues[param.identifier]"
			  type="date"
			  :placeholder="`请选择${param.name}`"
			  :readonly="param.fieldValueFormSrc!='input'"
			/>
			
			<!-- 日期时间类型 -->
			<el-date-picker
			  v-else-if="param.type === 'datetime'"
			  v-model="paramValues[param.identifier]"
			  type="datetime"
			  :placeholder="`请选择${param.name}`"
			  :readonly="param.fieldValueFormSrc!='input'"
			/>
		  </el-form-item>
		</el-form>
	  </div>
	  <el-empty v-else description="暂无参数" />
	  
	  <div style="margin-bottom: 18px;" v-if="!['save','update'].includes(testRow.exec)">
	  	<span class="title-form_primary">SQL语句</span>
	  </div>
	  
	  <div class="sql-content" v-if="!['save','update'].includes(testRow.exec)">
		<MonacoEditor
		  v-model="testSql"
		  :options="monacoOptions"
		  style="min-height:250px;"
		/>
	  </div>
	  
	  <div style="margin-bottom: 18px;">
	  	<span class="title-form_primary">测试结果</span>
	  </div>
      
      <div class="test-result">
		<div style="width: 100%;" v-if="testResult">
			<MonacoEditor
			  v-model="testResult"
			  :options="monacoOptions"
			  style="min-height:250px;"
			/>
		</div>
        
        <div v-else class="empty-result">
          <el-empty description="暂无测试结果" />
        </div>
      </div>
	  </el-scrollbar>
    </div>
	
	<template #footer>
	  <div class="dialog-footer">
		<el-button type="primary" @click="handleTest" :loading="loading">执行测试</el-button>
	  </div>
	</template>
	
  </el-drawer>
</template>

<script setup lang="ts">
	import { ref } from 'vue';
	import SqlAPI from '@/api/biz/sql';
	import type { FormInstance } from 'element-plus';
	import MonacoEditor from '@/components/MonacoEditor/index.vue';
	const dialog = ref({
		visible: false,
		title: '',
	});
	const emit = defineEmits(['closeDialog']);
	const loading = ref(false);
	const testSql = ref('');
	const testResult = ref<any>();
	const tableColumns = ref<string[]>([]);
	const testRow = ref<any>({});
	const paramField = ref<any[]>([]);
	const paramValues = ref<Record<string, any>>({});
	const paramFormRef = ref<FormInstance>();

	// Monaco Editor 配置
	const monacoOptions = ref({
		theme: 'vs-dark',
		language: 'sql',
		readOnly: true,
		automaticLayout: true,
		minimap: { enabled: false },
		lineNumbers: 'on',
		folding: true,
		wordWrap: 'on',
		fontSize: 14
	});

	const handleTest = async () => {
	  if (paramField.value.length > 0) {
		await paramFormRef.value?.validate();
	  }

	  try {
		loading.value = true;
		const res = await SqlAPI.test({
		  id: testRow.value.id,
		  values: paramValues.value
		});

		if (res) {
			testResult.value=JSON.stringify(res,null,2);
		}
	  } finally {
		loading.value = false;
	  }
	};

	async function openDialog(row?: any) {
		dialog.value = {
			visible: true,
			title: 'SQL测试'
		};
		testRow.value = row;
		if (testRow.value.content) {
			const content = JSON.parse(testRow.value.content);
			if (content) {
				testSql.value = content.sql;
				paramField.value = content.params || [];
				// 初始化参数值
				paramValues.value = {};
				paramField.value.forEach((param: any) => {
					paramValues.value[param.identifier] = param.defaultValue;
				});
				return;
			}
		}
		paramField.value = [];
		testSql.value = '';
		paramValues.value = {};
	}

	const closeDialog = () => {
		dialog.value.visible = false;
		dialog.value.title = '';
		emit('closeDialog');
		testSql.value = '';
		testRow.value = {};
		paramField.value = [];
		paramValues.value = {};
		testResult.value = "";
		tableColumns.value = [];
	};
	
	defineExpose({
	  openDialog, closeDialog
	});

</script>

<style lang="scss" scoped>
	.title-form_primary {
		font-style: normal;
		font-weight: 500;
		font-size: 14px;
		color: #1f2329;
		position: relative;
		padding-left: 5px;
	}
	
	.title-form_primary:before {
	    content: "";
	    width: 2px;
	    height: 14px;
	    background: var(--el-color-primary);
	    position: absolute;
	    top: 50%;
	    transform: translateY(-50%);
	    left: 0;
	}
	
	.drawer-content {
	  padding: 20px;
	  height: 100%;
	  display: flex;
	  flex-direction: column;
	  
	  .sql-info {
		margin-bottom: 20px;
		
		.info-item {
		  margin-bottom: 16px;
		  
			.label {
				font-weight: bold;
				margin-right: 8px;
				font-size: 14px;;
			}
		}
	  }
	  
	  .param-form {
		margin-bottom: 20px;
	  }
	  
	  .sql-content {
		margin-bottom: 20px;
		border: 1px solid var(--el-border-color);
		border-radius: 4px;
	  }
	  
	  .test-result {
		flex: 1;
		display: flex;
		flex-direction: column;
		
		.empty-result {
		  flex: 1;
		  display: flex;
		  align-items: center;
		  justify-content: center;
		}
	  }
	}
</style> 